package service

import (
	"quant/backend/db"
	"quant/backend/entity"
	"quant/backend/qmt"
	"sync"
	"time"

	"github.com/sirupsen/logrus"
)

var (
	subscribeService *SubscribeService
	subscribeMutex   sync.Mutex
)

type SubscribeService struct {
}

func NewSubscribeService() *SubscribeService {
	subscribeMutex.Lock()
	defer subscribeMutex.Unlock()
	if subscribeService == nil {
		subscribeService = &SubscribeService{}
	}
	return subscribeService
}

// Subscribe 开始订阅
func (s *SubscribeService) Subscribe() (string, error) {
	var err error
	var positions []qmt.PositionModel
	var codeList []string
	if positions, err = qmt.QueryStockPositions(); err != nil {
		return "", err
	} else {
		for _, dd := range positions {
			codeList = append(codeList, dd.StockCode)
			// t.Log(fmt.Sprintf("股票代码:%s,持仓数量:%d,可用数量:%d,持仓价格:%f,持仓市值:%f", dd.StockCode, dd.Volume, dd.CanUseVolume, dd.Price, dd.MarketValue))
		}
	}
	var pList []entity.PreferredEntity
	err = db.GetMySQL().Where("time = ?", time.Now().Format("20060102")).Find(&pList)
	if err != nil {
		return "", err
	}
	for _, pe := range pList {
		codeList = append(codeList, pe.StockCode)
	}

	if data, err := qmt.Subscribe(codeList); err != nil {
		logrus.Error("error:", err)
		return "", err
	} else {
		return data, nil
	}
}

// Unsubscribe 取消订阅
func (s *SubscribeService) Unsubscribe() (string, error) {
	if data, err := qmt.Unsubscribe(); err != nil {
		logrus.Error("error:", err)
		return "", err
	} else {
		return data, nil
	}
}
